package searchkeyword

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateSearchKeywordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateSearchKeywordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateSearchKeywordLogic {
	return &CreateSearchKeywordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateSearchKeywordLogic) CreateSearchKeyword(in *backend.SearchKeywordInfo) (*backend.BaseIDResp, error) {
	if in.Type == nil {
		return nil, errorx.NewInvalidArgumentError("searchKeyword.typeRequired")
	}

	now := time.Now()
	searchKeyword := &model.SearchKeyword{
		Type:      uint8(*in.Type),
		CreatedAt: now,
		UpdatedAt: now,
	}

	if in.Title != nil && len(strings.TrimSpace(*in.Title)) > 0 {
		searchKeyword.Title = strings.TrimSpace(*in.Title)
	}
	if in.LinkType != nil {
		searchKeyword.LinkType = uint8(*in.LinkType)
	}
	if in.LinkUrl != nil {
		searchKeyword.LinkURL = strings.TrimSpace(*in.LinkUrl)
	}
	if in.ObjectType != nil {
		searchKeyword.ObjectType = uint16(*in.ObjectType)
	}
	if in.ObjectId != nil {
		searchKeyword.ObjectID = *in.ObjectId
	}
	if in.Status != nil {
		searchKeyword.Status = uint8(*in.Status)
	} else {
		searchKeyword.Status = uint8(globalkey.StatusEnabled)
	}
	if in.Sort != nil {
		searchKeyword.Sort = uint16(*in.Sort)
	} else {
		searchKeyword.Sort = uint16(globalkey.SystemDefaultSort)
	}
	if in.StartedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
			searchKeyword.StartedAt = null.TimeFrom(localTime)
		}
	}
	if in.EndedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
			searchKeyword.EndedAt = null.TimeFrom(localTime.Add(time.Minute * -1))
		}
	}

	err := l.svcCtx.SearchKeyword.Insert(l.ctx, nil, searchKeyword)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseIDResp{
		Id:  searchKeyword.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
